package com.ysd.lis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysExtenFields;
import com.ysd.lis.request.*;
import com.ysd.lis.service.SysExtenFieldsService;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.ysd.lis.mapper.sys.SysExtenFieldsMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Cfz
 * @since 2023-12-20
 */
@Service
@Component
@Slf4j
public class SysExtenFieldsServiceImpl extends ServiceImpl<SysExtenFieldsMapper, SysExtenFields> implements SysExtenFieldsService {
    @Autowired
    SysExtenFieldsMapper sysExtenFieldsMapper;

    @Override
    public Result addExtenFields(SysExtenFields ExtenFields) {
        int insert = sysExtenFieldsMapper.insert(ExtenFields);
        if (insert > 0) {
            return Result.succ(1, "添加成功", ExtenFields);
        } else {
            return Result.fail(400, "添加失败", "");
        }
    }

    @Override
    public Result editExtenFields(SysExtenFields ExtenFields) {
        int updateById = sysExtenFieldsMapper.updateById(ExtenFields);
        if (updateById > 0) {
            return Result.succ(1, "提交成功", ExtenFields);
        } else {
            return Result.fail(400, "修改失败", "");
        }
    }

    @Override
    public Result deleteExtenFields(SysExtenFields ExtenFields) {
        SysExtenFields labBarCodeType = new SysExtenFields();
        BeanUtil.copyProperties(ExtenFields, labBarCodeType);
        labBarCodeType.setDelFlag(1);
        boolean b = this.updateById(labBarCodeType);
        if (b) {
            return Result.succ(1, "删除成功！", null);
        } else {
            return Result.fail("删除失败！");
        }
    }

    @Override
    public Result findExtenFieldsList(ExtenFieldsPageRequestDto pageParam) {
        LambdaQueryWrapper<SysExtenFields> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(SysExtenFields::getDelFlag, 0);
        lambdaQueryWrapper.eq(SysExtenFields::getModuleId, pageParam.getModuleId());
        lambdaQueryWrapper.eq(SysExtenFields::getMenuId, pageParam.getMenuId());
        List<SysExtenFields> sysExtenFields = sysExtenFieldsMapper.selectList(lambdaQueryWrapper);

        return Result.succ(1, "查询成功！", sysExtenFields);
    }

    @Override
    public Result findEditExtenFieldsList(ExtenFieldsPageRequestDto pageParam) throws JsonProcessingException {
        LambdaQueryWrapper<SysExtenFields> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(SysExtenFields::getDelFlag, 0);
        lambdaQueryWrapper.eq(SysExtenFields::getModuleId, pageParam.getModuleId());
        lambdaQueryWrapper.eq(SysExtenFields::getMenuId, pageParam.getMenuId());
        List<SysExtenFields> sysExtenFields = sysExtenFieldsMapper.selectList(lambdaQueryWrapper);

        Map<List<Object>, List<SysExtenFields>> groupedList = sysExtenFields.stream().collect(Collectors.groupingBy(s -> Arrays.asList(s.getGroupCode(), s.getGroupName(), s.getGroupSeq())));

        List<ExtenFieldsEditResponseDto> resList = new ArrayList<>();

        // 遍历分组后的数据
        Integer i = 0;
        for (Map.Entry<List<Object>, List<SysExtenFields>> entry : groupedList.entrySet()) {
            List<Object> key = entry.getKey(); // 分组的键
            List<SysExtenFields> opInGroup = entry.getValue(); // 分组的数据
            ExtenFieldsEditResponseDto res = new ExtenFieldsEditResponseDto();

            res.setTabCode(key.get(0).toString());
            res.setTabKey(key.get(0).toString());
            res.setTabTitle(key.get(1).toString());
            res.setTabSeq(Integer.parseInt(key.get(2).toString()));
            res.setTabValue(i);
            res.setEditFormItemIndex(0);
            ExtenFieldsEditResponseFormObjDto fmobj = new ExtenFieldsEditResponseFormObjDto();
            List<ExtenFieldsEditResponseFormItemDto> fmItems = new ArrayList<>();
            Integer j = 0;
            opInGroup.sort(new Comparator<SysExtenFields>() {
                @Override
                public int compare(SysExtenFields p1, SysExtenFields p2) {
                    return p1.getFieldSeq().compareTo(p2.getFieldSeq());
                }
            });
            for (SysExtenFields item : opInGroup) {
                ExtenFieldsEditResponseFormItemDto fmitm = new ExtenFieldsEditResponseFormItemDto();
                fmitm.setId(item.getId());
                fmitm.setCompType(item.getCompType());
                fmitm.setField(item.getField());
                fmitm.setTitle(item.getTitle());
                fmitm.setFieldCode(item.getFieldCode());
                fmitm.setFieldSeq(item.getFieldSeq());
                fmitm.setSpan(item.getSpan());
                fmitm.setAlign(item.getAlign());
                fmitm.setTitleAlign(item.getTitleAlign());
                fmitm.setTitleWidth(item.getTitleWidth());
                fmitm.setTitleColon(item.getTitleColon());
                fmitm.setTitleAsterisk(item.getTitleAsterisk());
                fmitm.setTitleOverflow(item.getTitleOverflow());
                fmitm.setShowTitle(item.getShowTitle());
                fmitm.setVisible(1);
                fmitm.setVertical(item.getVertical());
                fmitm.setClassName(item.getClassname());
                fmitm.setContentClassName(item.getContentclassname());
                fmitm.setContentStyle("");
                fmitm.setIsCurrent(j == 0);
                fmitm.setFieldSource(item.getFieldSource());
                fmitm.setFieldDefValue(item.getFieldDefValue());
                if (ToolsUtils.isNotEmpty(item.getFieldSource()) && item.getFieldSource().equals("3") && ToolsUtils.isNotEmpty(item.getFieldOptions())) {
                    ObjectMapper objectMapper = new ObjectMapper();
                    ExtenFieldsEditResponseFieldOptionsDto[] ops = objectMapper.readValue(item.getFieldOptions(), ExtenFieldsEditResponseFieldOptionsDto[].class);
                    fmitm.setFieldOptions(Arrays.asList(ops));
                }
                fmItems.add(fmitm);
                j++;
            }
            fmobj.setFormItems(fmItems);
            res.setFormObj(fmobj);
            resList.add(res);
            i++;
        }
        resList.sort(new Comparator<ExtenFieldsEditResponseDto>() {
            @Override
            public int compare(ExtenFieldsEditResponseDto p1, ExtenFieldsEditResponseDto p2) {
                return p1.getTabSeq().compareTo(p2.getTabSeq());
            }
        });

        int ii = 0;
        for (ExtenFieldsEditResponseDto item : resList) {
            item.setTabValue(ii);
            ii++;
        }
        return Result.succ(1, "查询成功！", resList);
    }

    @Override
    @Transactional
    public Result saveEditExtenFieldsList(SaveExtenFieldsEditRequestDto input) throws JsonProcessingException {
        LambdaQueryWrapper<SysExtenFields> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(SysExtenFields::getDelFlag, 0);
        lambdaQueryWrapper.eq(SysExtenFields::getModuleId, input.getModuleId());
        lambdaQueryWrapper.eq(SysExtenFields::getMenuId, input.getMenuId());
        List<SysExtenFields> sysExtenFields = sysExtenFieldsMapper.selectList(lambdaQueryWrapper);

        List<SysExtenFields> listAdd = new ArrayList<>();
        List<SysExtenFields> listModify = new ArrayList<>();
        for (ExtenFieldsEditResponseDto item : input.getList()) {
            for (ExtenFieldsEditResponseFormItemDto itm : item.getFormObj().getFormItems()) {
                //正常修改
                if (ToolsUtils.isNotEmpty(itm.getId())) {
                    SysExtenFields entry = new SysExtenFields();
                    BeanUtil.copyProperties(itm, entry);
                    entry.setGroupCode(item.getTabKey());
                    entry.setGroupName(item.getTabTitle());
                    entry.setGroupSeq(item.getTabValue());
                    if (ToolsUtils.isNotEmpty(itm.getFieldSource()) && ToolsUtils.isNotEmpty(itm.getFieldOptions())) {
                        ObjectMapper objectMapper = new ObjectMapper();
                        entry.setFieldOptions(objectMapper.writeValueAsString(itm.getFieldOptions()));
                    }
                    listModify.add(entry);
                }
                if (!ToolsUtils.isNotEmpty(itm.getId())) {
                    SysExtenFields entry = new SysExtenFields();
                    BeanUtil.copyProperties(itm, entry);
                    entry.setGroupCode(item.getTabKey());
                    entry.setGroupName(item.getTabTitle());
                    entry.setGroupSeq(item.getTabValue());
                    entry.setModuleId(input.getModuleId());
                    entry.setMenuId(input.getMenuId());
                    if (ToolsUtils.isNotEmpty(itm.getFieldSource()) && ToolsUtils.isNotEmpty(itm.getFieldOptions())) {
                        ObjectMapper objectMapper = new ObjectMapper();
                        entry.setFieldOptions(objectMapper.writeValueAsString(itm.getFieldOptions()));
                    }
                    listAdd.add(entry);
                }
            }

        }
        List<SysExtenFields> delList = sysExtenFields.stream().filter(pp -> !listModify.stream().map(SysExtenFields::getId).collect(Collectors.toList()).contains(pp.getId())).collect(Collectors.toList());
        if (ToolsUtils.isNotEmpty(delList)) {
            for (SysExtenFields item : delList) {
                item.setDelFlag(1);
                listModify.add(item);
            }
        }
        boolean uFlag = this.updateBatchById(listModify);
        boolean aFlag = this.saveBatch(listAdd);
        if (ToolsUtils.isNotEmpty(listModify) && ToolsUtils.isNotEmpty(listAdd)) {
            return Result.succ(uFlag && aFlag ? 1 : 0, uFlag && aFlag ? "提交成功" : "提交失败", null);
        }
        if (ToolsUtils.isNotEmpty(listModify) && !ToolsUtils.isNotEmpty(listAdd)) {
            return Result.succ(uFlag ? 1 : 0, uFlag ? "提交成功" : "提交失败", null);
        }
        if (!ToolsUtils.isNotEmpty(listModify) && ToolsUtils.isNotEmpty(listAdd)) {
            return Result.succ(aFlag ? 1 : 0, aFlag ? "提交成功" : "提交失败", null);
        }
        return Result.fail("没有要保存的数据");
    }
}
